var API = (function(){
    
const BASE_URL = 'https://study.duyiedu.com';

const TOKEN_KEY = 'token_key';

function get(path) {
    const headers = {};
    if (localStorage.getItem(TOKEN_KEY)) {
        headers.authorization = `Bearer ${localStorage.getItem(TOKEN_KEY)}`
    };
    return fetch(BASE_URL + path, {
        headers
    })
}

function post(path, bodyObj) {
    const headers = {
        'Content-Type': 'application/json',
    };
    if (localStorage.getItem(TOKEN_KEY)) {
        headers.authorization = `Bearer ${localStorage.getItem(TOKEN_KEY)}`
    };
    return fetch(BASE_URL + path, {
        headers,
        method: 'POST',
        body: JSON.stringify(bodyObj),//stringify将js对象转化为符合json标准的字符串，parse将符合json标准的字符串转化为js对象
    });
}

async function reg(userInfo) {
    const resp = await post('/api/user/reg', userInfo);//获取到响应头和状态码
    return await resp.json();//等待响应体传输完成，一边传输一边解析为json格式的对象？
}

async function login(userInfo) {
    const resp = await post('/api/user/login', userInfo);
    const body = await resp.json();
    if (body.code === 0) {
        const token = resp.headers.get('authorization');
        localStorage.setItem(TOKEN_KEY, token);
    }
    return body;
}

async function profile() {
    const resp = await get('/api/user/profile');
    return await resp.json();
}

async function exists(loginId) {
    const resp = await get('/api/user/exists?loginId=' + loginId);
    return await resp.json();
}

async function sendChat(content) {
    const resp = await post('/api/chat', {
        content,
    })
    return await resp.json();
}

async function getHistory(){
    const resp = await get('/api/chat/history');
    return await resp.json(); 
}

function loginOut(){
    localStorage.removeItem(TOKEN_KEY);//删掉token，退出登录
}
return {
    reg,
    login,
    exists,
    profile,
    sendChat,
    getHistory,
    loginOut,
};
})();